
package com.jprocms.module.cms.controller.admin.sitetpl;

import cn.hutool.core.io.file.FileNameUtil;
import com.jpro.framework.common.exception.ServerException;
import com.jprocms.module.cms.service.sitetpl.IResFile;
import com.jprocms.module.cms.service.sitetpl.TplService;
import com.jprocms.module.cms.util.FileUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;
import java.util.List;

import static com.jpro.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.jprocms.module.cms.enums.ErrorCodeConstants.*;

public abstract class AbstractTplAndResourceController {

    private final List<String> whitelist = Arrays.asList("woff2", "eot", "woff", "ttf", "svg", "jpg", "jpeg", "png", "gif", "css", "js", "bmp", "ico", "map",
            "mp4", "m4v", "mov", "qt", "avi", "flv", "wmv", "asf", "mpeg", "mpg", "vob", "rmvb", "rm", "ts", "3gp", "asf", "wmv", "mkv", "dat",
            "mp3", "wav", "aif", "au", "ram", "wma", "mmf", "amr", "flac", "aac", "cur", "htc", "swf");

    /**
     * 校验参数是否为空
     *
     * @param names 参数
     * @throws ServerException 异常
     */
    protected void validBlank(Object... names) throws ServerException {
        for (Object name : names) {
            boolean isNull = false;
            if (name instanceof String) {
                isNull = StringUtils.isBlank((String) name);
            } else if (name == null) {
                isNull = true;
            }
            if (isNull) {
                throw exception(COMMON_PARAM_ERROR);
            }
        }
    }

    /**
     * 添加模板校验
     *
     * @param path    文件路径（包含文件名）
     * @param tplPath 站点对应路径
     * @throws ServerException 异常
     */
    protected void validSave(String path, String tplPath) throws ServerException {
        //检查操作是否再指定目录下
        FileUtil.isValidFilename(tplPath, path);
        //文件已存在抛出异常
        if (vldExistFile(path)) {
            throw exception(COMMON_PARAM_ERROR);
        }
    }

    /**
     * 文件不存在校验
     *
     * @param path    文件路径（包含文件名）
     * @param tplPath 站点对应路径
     * @throws ServerException 异常
     */
    protected void validFileExist(String path, String tplPath) throws ServerException {
        //检查操作是否再指定目录下
        FileUtil.isValidFilename(tplPath, path);
        //文件不存在抛出异常
        if (!vldExistFile(path)) {
            throw exception(FILE_NOT_EXISTS);
        }
    }

    /**
     * 修改模板校验
     *
     * @param oldName 原文件名
     * @param newName 新文件名
     * @param tplPath 站点对应路径
     * @throws ServerException 异常
     */
    protected void validReName(String oldName, String newName, String tplPath) throws ServerException {
        //检查操作是否再指定目录下
        FileUtil.isValidFilename(tplPath, newName);
        //原文件不存在抛出异常
        if (!vldExistFile(oldName)) {
            throw exception(COMMON_PARAM_ERROR);
        }
        //修改后的文件名存在抛出异常
        if (vldExistFile(newName)) {
            throw exception(COMMON_PARAM_ERROR);
        }
    }

    /**
     * 导入文件校验
     *
     * @param file 导入文件
     * @throws ServerException 异常
     */
    protected void validateFile(MultipartFile file) throws ServerException {
        //判断文件是否存在
        if (file == null) {
            throw exception(FILE_NOT_EXISTS);
        }
        String filename = file.getOriginalFilename();
        boolean checkFilename = false;
        String type1 = "/";
        if (type1.contains(filename)) {
            checkFilename = true;
        }
        String type2 = "\\";
        if (type2.contains(filename)) {
            checkFilename = true;
        }
        String type3 = "\0";
        if (type3.contains(filename)) {
            checkFilename = true;
        }
        if (checkFilename) {
            throw exception(TPL_FILE_NOT_SUPPORT);
        }
    }

    protected void validateFileFormat(MultipartFile file) throws ServerException {
        String suffix = FileNameUtil.getSuffix(file.getOriginalFilename());
        if (StringUtils.isBlank(suffix) || !whitelist.contains(suffix.toLowerCase())) {
            throw exception(TPL_FILE_NOT_SUPPORT);
        }
    }

    /**
     * 判断文件是否存在
     *
     * @param name 文件路径
     * @return true 文件存在，false 文件不存在
     */
    public boolean vldExistFile(String name) throws ServerException {
        if (StringUtils.isBlank(name)) {
            return true;
        }
        IResFile entity = null;
        try {
            entity = tplService.get(name);
        } catch (Exception e) {
            return false;
        }
        if (entity != null) {
            return true;
        }
        return false;
    }

    protected void validateBindingResult(BindingResult result) throws ServerException {
        /* 对字段进行校验 */
        if (result.hasErrors()) {
            /* 获取非法参数异常信息对象，并抛出异常。 */
            throw exception(COMMON_PARAM_ERROR);
        }
    }

    @Autowired
    private TplService tplService;
}
